package com.ge.pp;

import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;

import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListModel;
import javax.swing.ListSelectionModel;

public class CaseBrowser extends JDialog {
	JList caseListView;
	Vector<Case> mainCaseList;
	Vector<Case> selectedCases;
	
	public CaseBrowser(JFrame parent, Vector<Case> caseList) throws Exception {
		super(parent, "Case Browser", true);
		
		try
		{
		
		mainCaseList = caseList;
		selectedCases = new Vector<Case>();
		
		Container cp = getContentPane();
		BoxLayout mainLayout = new BoxLayout(cp, BoxLayout.Y_AXIS);
	    cp.setLayout(mainLayout);
	   
	    DefaultListModel caseListModel = new DefaultListModel();
	    for(int i=0; i< caseList.size(); i++)
	    	caseListModel.addElement(caseList.get(i).name);
	    caseListView = new JList(caseListModel);	   
	    caseListView.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
	    caseListView.setLayoutOrientation(JList.VERTICAL);
	    caseListView.setMinimumSize(new Dimension(200,400));
	    caseListView.setSize(200,400);
	    JScrollPane caseScroller = new JScrollPane(caseListView);
	    
	    JLabel label = new JLabel("Available Cases");
	    label.setAlignmentX(Component.LEFT_ALIGNMENT);
	   
	    JPanel buttonPane = new JPanel();
	    BoxLayout buttonBox = new BoxLayout(buttonPane, BoxLayout.LINE_AXIS);
	    JButton addCase = new JButton("Add Case");
	    JButton cancel = new JButton("Close");
	    
	    addCase.addActionListener(new ActionListener() {
	    	@Override
			public void actionPerformed(ActionEvent e) {
	    		int [] selections = caseListView.getSelectedIndices();
	    		ListModel model = caseListView.getModel();
	    		for(int i=0; i<selections.length; i++) {
	    			String caseName = (String)model.getElementAt(selections[i]);					
					
					for(int j=0; j<mainCaseList.size(); j++) {
						Case c = mainCaseList.get(j);
						if (c.name.equals(caseName)) {
							selectedCases.add(c);
							break;
						}
					}
	    		}
				
				dispose();
			}	    
	    });
	    
	    cancel.addActionListener(new ActionListener() {
	      public void actionPerformed(ActionEvent e) {	    	  
	        dispose(); // Closes the dialog
	      }
	    });
	    
	    cp.add(label);
	    cp.add(caseScroller);
	    buttonPane.add(addCase);
	    buttonPane.add(cancel);
	    cp.add(buttonPane);
	    setSize(300, 500);
		}
		catch(Exception e)
		{
			throw e;
		}
	    //pack();
	}
	
	public Vector<Case> GetCases() {
		return this.selectedCases;
	}
}
